from datetime import datetime
from flask_login import UserMixin
from app import db, login_manager
from app.utils import SecurityUtil

class User(UserMixin, db.Model):
    __tablename__ = 'users'
    
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(64), unique=True, index=True)
    email = db.Column(db.String(120), unique=True, index=True)
    password_hash = db.Column(db.String(128))
    avatar = db.Column(db.String(128), default='default.jpg')
    about_me = db.Column(db.Text())
    member_since = db.Column(db.DateTime(), default=datetime.utcnow)
    last_seen = db.Column(db.DateTime(), default=datetime.utcnow)
    
    # 关系
    questions = db.relationship('Question', backref='author', lazy='dynamic')
    answers = db.relationship('Answer', backref='author', lazy='dynamic')
    likes = db.relationship('Like', backref='user', lazy='dynamic')
    
    @property
    def password(self):
        """属性装饰器: 阻止密码的直接访问，提高安全性
        
        尝试读取password属性时将抛出异常
        """
        raise AttributeError('密码不是可读属性')
    
    @password.setter
    def password(self, password):
        """属性设置器: 设置密码时自动进行哈希处理
        
        存储哈希值而非明文密码，提高安全性
        """
        self.password_hash = SecurityUtil.generate_password_hash(password)
    
    def verify_password(self, password):
        """验证密码是否正确"""
        return SecurityUtil.check_password_hash(self.password_hash, password)
    
    def ping(self):
        """更新用户的最后在线时间"""
        self.last_seen = datetime.utcnow()
        db.session.add(self)
    
    def __repr__(self):
        return f'<用户 {self.username}>'

@login_manager.user_loader
def load_user(user_id):
    """装饰器: Flask-Login的用户加载回调函数
    
    从session中的user_id加载用户对象
    """
    return User.query.get(int(user_id)) 